<template>
  <div class="no-background-container">
    <header-component />
    <div style="height: 60px"></div>
    <search-form-qvil
      :form-data="queryForm"
      :form-items="searchParams()"
      :loading="listLoading"
      @submit="queryData"
      @update:form-data="updateQueryForm"
    >
      <template #actions>
        <el-button type="primary" @click="handleAdd">新增{{ moduleName }}</el-button>
      </template>
    </search-form-qvil>

    <table-qvil
      :columns="tableColumns"
      :data="list"
      :loading="listLoading"
      :pagination="{
        page: queryForm.page,
        limit: queryForm.limit,
        total: total,
      }"
      :total="total"
      @delete="handleDelete"
      @details="handleDetails"
      @edit="handleEdit"
      @page-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
      <template #column-surround="{ row }">
        <point-map :initial-points="row.surround" @save="(points) => handleSaveFence(points, row)" />
      </template>
      <template #column-operations="{ row }">
        <el-button size="small" type="primary" @click="handleEdit(row)">
          <el-icon><edit-pen /></el-icon>
          编辑
        </el-button>
        <el-button size="small" type="danger" @click="handleDelete(row)">
          <el-icon><delete /></el-icon>
          删除
        </el-button>
      </template>
    </table-qvil>

    <form-dialog-qvil
      v-model="showFormDialog"
      :fields="addParams"
      :form-data="form"
      :loading="formLoading"
      :title="isEditMode ? '编辑' : '新增'"
      @confirm="handleFormSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import Public from '~/src/api/public/index.ts'
import PointMap from '~/src/components/Map/index.vue'
import HeaderComponent from '../components/header.vue'
import type { Place } from './config.ts'
import { addParams, moduleApi, moduleName, searchParams, tableColumns } from './config.ts'
// 路由相关
const route = useRoute()
const routeName = computed(() => route.meta.title || '')

// 数据相关
const list = ref<Place[]>([])
const total = ref(0)
const listLoading = ref(false)
const formLoading = ref(false)
const showFormDialog = ref(false)
const isEditMode = ref(false)
const form = ref<Partial<Place>>({})

// 查询表单
interface QueryForm {
  page: number
  limit: number
  [key: string]: any
}

const queryForm = ref<QueryForm>({
  page: 1,
  limit: 20,
})

// 初始化查询表单
onMounted(() => {
  searchParams().forEach((param) => {
    queryForm.value[param.prop] = null
  })
  fetchData()
})

// 更新查询表单
const updateQueryForm = (newQueryForm: QueryForm) => {
  queryForm.value = { ...newQueryForm }
}

// 获取数据
const fetchData = async () => {
  listLoading.value = true
  try {
    const response = await Public.getDetailApi({ url: moduleApi, params: queryForm.value })
    const { code, result } = response as { code: number; result: { rows: Place[]; count: number } }
    if (code === 0) {
      list.value = result.rows
      total.value = result.count
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    listLoading.value = false
  }
}

// 分页处理
const handleSizeChange = (value: number) => {
  updatePagination({ page: 1, limit: value })
}

const handleCurrentChange = (value: number) => {
  updatePagination({ page: value })
}

const updatePagination = (params: { page?: number; limit?: number }) => {
  Object.assign(queryForm.value, params)
  fetchData()
}

// 查询数据
const queryData = () => {
  updatePagination({ page: 1 })
}

// 新增
const handleAdd = () => {
  form.value = {}
  isEditMode.value = false
  showFormDialog.value = true
}

// 编辑
const handleEdit = (row: Place) => {
  form.value = { ...row }
  isEditMode.value = true
  showFormDialog.value = true
}

// 删除
const handleDelete = (row: Place) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await Public.delApi({ url: moduleApi, id: row.id })
        ElMessage.success('删除成功!')
        fetchData()
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 查看详情
const handleDetails = (row: Place) => {
  // TODO: 实现详情查看功能
  console.log('查看详情:', row)
}

// 表单提交
const handleFormSubmit = async (formData: Place) => {
  formLoading.value = true
  try {
    if (isEditMode.value) {
      await Public.editApi({ url: moduleApi, data: formData })
      ElMessage.success('编辑成功')
    } else {
      await Public.addApi({ url: moduleApi, data: formData })
      ElMessage.success('新增成功')
    }
    showFormDialog.value = false
    fetchData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    formLoading.value = false
  }
}

// 处理围栏保存
const handleSaveFence = async (points: string[], row: Place) => {
  try {
    await Public.editApi({
      url: moduleApi,
      data: {
        ...row,
        surround: points,
      },
    })
    ElMessage.success('保存成功')
    fetchData() // 刷新数据
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}
</script>

<style scoped>
.no-background-container {
  @apply w-full min-h-screen bg-white;
}

.qs-y-table-header {
  @apply flex flex-col gap-4 p-4 bg-white border-b border-gray-200;
}

.header-query {
  @apply flex justify-between items-center;
}
</style>
